import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import css from './countDown.module.scss'
export default class LotteryCountDown extends PureComponent {
    
    static propTypes = {
        prizes: PropTypes.object
    }

    state = {
        timer: null,
        day: 0,
        hour: 0,
        minute: 0
    }

    get hasPrizes() {
        return !!this.props.prizes
    }

    get title() {
        let data = '开奖倒计时'
        if (this.hasPrizes) {
            const status = this.props.prizes.status
            switch(status) {
                case 0:
                    data = '开奖倒计时'
                    break
                case 1:
                    data = '正在开奖中...'
                    break
                case -1:
                    data = '该抽奖活动已失效'
                    break
                default:
                    data = '开奖倒计时'
            }
        }
        return data
    }

    // 开奖时间
    get openTime() {        
        return this.props?.prizes?.lottery_time ?? 0
    }

    addZero = val => {
        return (val + '').padStart(2, '0')
    }

    countTime = () => {
        const nowTime = Math.ceil(new Date().getTime() / 1000)
        const diff = this.openTime - nowTime
        let diffDate = Math.floor(diff / 60 / 60 / 24)
        diffDate = diffDate < 0 ? 0 : diffDate
        let diffHour = Math.floor((diff - 24 * diffDate * 60 * 60) / 60 / 60)
        diffHour = diffHour < 0 ? 0 : diffHour
        let diffMinute = Math.ceil((diff - 24 * diffDate * 60 * 60 - 60 * diffHour * 60) / 60)
        diffMinute = diffMinute < 0 ? 0 : (diffMinute > 59 ? 59 : diffMinute)
        this.setState({
            day: this.addZero(diffDate),
            hour: this.addZero(diffHour),
            minute: this.addZero(diffMinute)
        }) 
    }

    start = () => {
        this.countTime()
        const interval = setInterval(() => {
            this.countTime()
        }, 30000)
        this.setState({
            timer: interval
        })
    }

    stop = () => {
        clearInterval(this.state.timer)
        this.setState({
            timer: null
        })
    }

    componentDidMount() {     
        this.start()   
    }

    componentWillUnmount() {
        this.stop()
    }

    render() {
        const { day, hour, minute } = this.state
        return (
            <div className={css["wrap"]}>
                <div className={css["title"]}>{ this.title }</div>
                <div className={css["clock-wrap"]}>
                    <span className="clock-value">{day}</span>
                    <span className="clock-label">天</span>
                    <span className="clock-value">{hour}</span>
                    <span className="clock-label">时</span>
                    <span className="clock-value">{minute}</span>
                    <span className="clock-label">分</span>
                </div>                
            </div>
        )
    }
}
